import { Button, Table, Modal, Input, Form, Checkbox } from 'antd';
import { FormOutlined, CloseOutlined } from '@ant-design/icons';
import React, { useState, useEffect } from 'react';
import intl from 'react-intl-universal';
import axios from 'axios';
import $ from 'jquery';
import RoleMember from './roleMember';
import { storage, userMenu } from '../../utils/localstorage';
import './role.css';


const layout = { labelCol: {span: 8,}, wrapperCol: {span: 16,}, };

const Role = () => {
  // 表格每一列的表头信息
  const columns = [
    {
      title: intl.get('roleName'),
      dataIndex: 'name',
      align: 'center',
      width: '300px',
    },
    {
      title: intl.get('roleDescription'),
      dataIndex: 'description',
      align: 'center',
      width: '500px',
    },
    {
      title: intl.get('roleMenu'),
      dataIndex: 'menu',
      align: 'center',
      width: '400px',
    },
    {
      title: intl.get('roleOperation'),
      dataIndex: 'operation',
      align: 'center',
    },
  ];


  // 公共
  const [onChange, setOnChange] = useState(true);     // 记录当前页面的角色列表是否发生变化，如增加、删除、修改了角色
  const [rowInfo, setRowInfo] = useState({});         // 记录某个角色的数据，即表格中一行的数据
  const [ifRecord, setIfRecord] = useState(false);    // 判定角色数据是否记录


  // 从后端获取角色数据
  const [roleData, setRoleData] = useState([]);       // 保存数据
  useEffect(() => {
    const getHomeData = async () => {
      const resOfRoleNum = await axios('/home/role'); // async、await、axios：在组件渲染之前获取数据
      if (resOfRoleNum.data.status === 1) {           // 状态码为1，表示请求成功
        setRoleData(resOfRoleNum.data.data)
      } else {
        alert("无法获取用户列表");
      }
    };
    onChange && getHomeData();
    setOnChange(false);
  }, [onChange]);                                     // 当页面数据有变化时获取数据


  // 增加、修改角色，查看角色成员的Modal窗口
  const [modalWidth, setModalWidth] = useState("520px");
  const [showModal, setShowModal] = useState({
    ifShow: false,
    title: 'Modal',
    children: {},
  });
  const hideModal = () => {
    setModalWidth("520px");
    setShowModal({
      ifShow: false,
      title: 'Modal',
      children: {},
    });
  };


  // 角色菜单
  const roleMenu = [];
  userMenu.map((item) => {
    roleMenu.push({
      label: item,
      value: item
    });
  });


  // 添加角色
  const doAddRole = (values) => {         // 将添加的角色信息传给后端，存入数据库
    console.log(values)
    $.ajax({
      url: '/home/role/add',
      data: values,
      traditional: true,
      type: 'post',
      dataType: 'json',
      success: function(result) {
        if (result.status === 1) {
          setOnChange(true);              // 添加成功，刷新页面
          hideModal();
        } else {
          alert('角色名称已被使用，请更换');  // 添加失败，可能是角色名称已被使用
        }
      },
      error: function(err) {      
        alert(JSON.stringify(err));       // 与后端连接失败，提示信息
      }
    });
  };
  const addRole = () => {                 // 添加角色按钮 的响应函数
    setShowModal({                        // 弹出添加角色 窗口
      ifShow: true,
      title: intl.get('addRole'),
      children: 
        <Form {...layout} validateMessages={{ required: 'Name is required!', }} onFinish={doAddRole}> {/* 表单，点击提交按钮，触发doAddRole事件 */}
          <Form.Item name='roleName' label="Name" rules={[{required: true, max: 32},]}>
            <Input />
          </Form.Item>
          <Form.Item name='roleDescription' label="Introduction">
            <Input.TextArea />
          </Form.Item>
          <Form.Item name='roleMenu' label="Menu">
            <Checkbox.Group options={roleMenu} />
          </Form.Item>
          <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
            <Button type="primary" htmlType="submit" className='doAddRole'>{intl.get('submit')}</Button>
          </Form.Item>
        </Form>
    });
  };


  // 修改角色
  const [update, setUpdate] = useState(false);    // 是否执行'修改角色'操作的标志
  const updateRole = () => {                      // 点击修改图标 的响应函数
    setIfRecord(true);
    setUpdate(true);
  };
  const doUpdateRole = (values) => {
    console.log(values)
    $.ajax({
      url: '/home/role/update',
      data: values,
      traditional: true,
      type: 'post',
      dataType: 'json',
      success: function(result) {
        if (result.status === 1) {
          setOnChange(true);                      // 修改成功，刷新页面
          hideModal();                            // 隐藏修改窗口
        } else {
          alert('角色名称已被使用，请更换');          // 修改失败，可能是角色名称已被使用
        }
      },
      error: function(err) {
        alert(JSON.stringify(err));               // 连接服务器失败，提示信息
      }
    });
  };
  const updateModal = () => {
    setShowModal({
      ifShow: true,
      title: intl.get('updateRole'),
      children: 
        <Form {...layout} validateMessages={{ required: 'Name is required!', }} onFinish={doUpdateRole} initialValues={{rid:rowInfo.key, roleName:rowInfo.name, roleDescription:rowInfo.description}}>
          <Form.Item name='rid'>
            <Input hidden={true} />
          </Form.Item>
          <Form.Item name='roleName' label="Name" rules={[{required: true, max: 32},]}>
            <Input />
          </Form.Item>
          <Form.Item name='roleDescription' label="Introduction">
            <Input.TextArea />
          </Form.Item>
          <Form.Item name='roleMenu' label="Menu">
            <Checkbox.Group options={roleMenu} />
          </Form.Item>
          <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
            <Button type="primary" htmlType="submit" className='doAddRole'>{intl.get('submit')}</Button>
          </Form.Item>
        </Form>
    });
  };
  useEffect(() => {
    update && ifRecord && updateModal();          
    setIfRecord(false);
    setUpdate(false);
  }, [update]);   // eslint-disable-line react-hooks/exhaustive-deps


  // 选中行
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const start = () => {
    setSelectedRowKeys([]);
  };
  const onSelectChange = (newSelectedRowKeys, record) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    console.log('r', record)
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;


  // 左侧勾选框删除角色
  const deleteSelectedRole = (val) => {
    console.log('arrr',selectedRowKeys)
    $.ajax({
      url: '/home/role/delete',
      type: 'post',
      data: {'arr': selectedRowKeys},
      traditional: 'true',
      dataType: 'json',
      success: function(result) {
        if (result.status === 1) {
          setOnChange(true);
          alert(intl.get('succeedToDelete'));
        } else {
          alert(result.msg);
        }
      },
      error: function(err) {
        alert(err);
      }
    });
  }


  // 点击删除图标 删除角色
  const [del, setDel] = useState(false);
  const deleteRole = () => {
    setIfRecord(true);
    setDel(true);
  };
  const doDeleteRole = () => {
    let arr = [];
    arr.push(rowInfo.key);
    $.ajax({
      url: '/home/role/delete',
      type: 'post',
      data: {"arr": arr},
      traditional: true,                      // 让数组正确转换成JSON字符串 
      dataType: 'json',
      success: function(result) {
        if (result.status === 1) {
          setOnChange(true);
          alert(intl.get('succeedToDelete'));
        } else {
          alert(result.msg);
        }
      },
      error: function(err) {
        alert(JSON.stringify(err));
      }
    });
  };
  useEffect(() => {
    del && ifRecord && doDeleteRole();          
    setIfRecord(false);
    setDel(false);
  }, [del]);  // eslint-disable-line react-hooks/exhaustive-deps


  // 查看角色成员
  const [query, setQuery] = useState(false);          // 是否执行'查看角色成员'操作的标志
  const checkRoleMember = () => {                     // 查看角色成员按钮的响应函数
    setIfRecord(true);                                // 点击按钮，该行数据已记录
    setQuery(true);                                   // 执行查看角色成员操作
  };
  const queryModal = () => {
    setModalWidth("1500px");
    setShowModal({
      ifShow: true,
      title: intl.get('roleMember'),
      children: 
        <RoleMember rowInfo={rowInfo} />
    });
  };
  useEffect(() => {                                   
    query && ifRecord && queryModal();
    setIfRecord(false);
    setQuery(false);
  }, [query]);  // eslint-disable-line react-hooks/exhaustive-deps                                        


  // 填充表格每一行的数据
  const data = [];
  roleData.map(function (item) {
    data.push({
      key: item.rid,                                  // 角色id作为key
      name: item.roleName,                            // 角色名称
      description: item.roleDescription,              // 角色描述
      menu: item.roleMenu,
      operation: <div key={item.rid} className='roleOperation'>      {/* 表格最右一列，对该角色的操作 */}
        <button onClick={checkRoleMember}>{intl.get('userOfRole')}</button>   {/* 查看角色成员 */}
        <FormOutlined onClick={updateRole} className='editRole' />                                 {/* 修改 */}
        <CloseOutlined onClick={deleteRole} className='deletRole' />          {/* 删除 */}
      </div>,
    });
  });


  return (
    <div>
      <div className='roleTable'>
        <div style={{ marginBottom: 16, }}>
          <Button type="primary" onClick={start} disabled={!hasSelected} style={{ width: '78px' }}>{intl.get("reset")}</Button> {/* 重置选项 */}
          <Button type="primary" onClick={deleteSelectedRole} style={{ width: '78px' }}>{intl.get("deleteRole")}</Button>       {/* 删除 */}
          <Button type="primary" onClick={addRole} style={{ width: '78px' }}>{intl.get("addRole")}</Button>                     {/* 添加 */}
        </div>
        <Table rowSelection={rowSelection} columns={columns} dataSource={data}
          onRow={(record) => {
            return ({
              onClick: () => setRowInfo(record)
            })
          }}
        />
      </div>
      <Modal destroyOnClose='true' title={showModal.title} visible={showModal.ifShow} width={modalWidth}
        onOk={hideModal} onCancel={hideModal} okText={intl.get('yes')} cancelText={intl.get('no')}>
        {showModal.children}
      </Modal>
    </div>
  );
};

export default Role;